package com.example.lt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.lt.constant.MessageConstant;
import com.example.lt.constant.MinioPicPathConstant;
import com.example.lt.constant.PicPathConstant;
import com.example.lt.exception.MinioOperateException;
import com.example.lt.mapper.CommentMapper;
import com.example.lt.mapper.SingerMapper;
import com.example.lt.pojo.entity.Comment;
import com.example.lt.pojo.entity.Singer;
import com.example.lt.pojo.entity.Song;
import com.example.lt.pojo.vo.SingerVO;
import com.example.lt.result.Result;
import com.example.lt.service.CommentService;
import com.example.lt.service.MinioService;
import com.example.lt.service.SingerService;
import com.example.lt.service.SongService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author 小涛Tao
 * @Date: 2024/05/31/15:59
 * version 1.0 注释：
 **/
@Service
@RequiredArgsConstructor
public class SingerServiceImpl extends ServiceImpl<SingerMapper, Singer> implements SingerService {

    private final SingerMapper singerMapper;

    private final SongService songService;

    private final MinioService minioService;

    private final CommentMapper commentMapper;

    /**
     * 更新歌手图片
     * @param picFile
     * @param id
     * @return
     */
    public Result updateSingerPic(MultipartFile picFile, int id) {
        String originalFilename = picFile.getOriginalFilename(); // 获取前端传来的图片名称
        String imgPath = PicPathConstant.SINGER_PIC_PATH + originalFilename; // 生成新的图片访问路径
        Singer singer = Singer.builder().id(id).pic(imgPath).build();
        // 更新minio中的歌手图片
        String s = minioService.uploadFile(MinioPicPathConstant.SINGER_IMAGES_PATH, originalFilename, picFile);

        int flag = singerMapper.updateById(singer); // 更新数据库中存储的访问路径

        if (s.equals("File uploaded successfully.") && flag > 0) {
            return Result.success(MessageConstant.ALTER_SUCCESS, imgPath); // 成功，同时返回新的图片访问路径
        } else {
            throw new MinioOperateException(MessageConstant.ALTER_FAIL); // 失败
        }
    }

    /**
     * 管理端删除歌手
     * @param id
     * @return true：删除成功  false：删除失败
     */
    @Transactional
    public boolean deleteSinger(Integer id) {
        Singer singer = singerMapper.selectById(id);
        int flagOne = singerMapper.deleteById(id);
        if (!(flagOne > 0)) { // 如果没有删除任何记录则返回false
            return false;
        }

        List<Song> songList = songService.lambdaQuery().eq(Song::getSingerId, id).list();

        List<Integer> songIds = songList.stream().map(Song::getId).collect(Collectors.toList());

        boolean flagTwo = songService.removeByIds(songIds); // 歌手被删除了，要删除这个歌手的歌曲
        if (!flagTwo) {
            return false;
        }

        for (Integer songId : songIds) { // 根据歌曲id集合删除歌曲的评论
            commentMapper.delete(new QueryWrapper<Comment>().eq("song_id", songId));
        }

        // 删除minio中存储的歌手图片
        String pic = singer.getPic();
        if (!pic.equals(PicPathConstant.DEFAULT_SINGER_PIC) && "minio/".equals(pic.substring(0,6))) {
            String fileName = pic.substring(pic.lastIndexOf("/") + 1);
            minioService.deleteFile(MinioPicPathConstant.SINGER_IMAGES_PATH, fileName);
        }

        // 删除minio中存储的歌曲音频
        List<String> urlPathList = songList.stream().map(Song::getUrl).collect(Collectors.toList());
        for (String urlPath : urlPathList) {
            if (urlPath == null || !"song/".equals(urlPath.substring(0,5))) {
                continue;
            }
            String fileName = urlPath.substring(urlPath.lastIndexOf("/") + 1);
            minioService.deleteFile(MinioPicPathConstant.SONG_PATH, fileName);
        }

        // 删除minio中存储的歌曲图片
        List<String> picPathList = songList.stream().map(Song::getPic).collect(Collectors.toList());
        for (String picPath : picPathList) {
            if (picPath.equals(PicPathConstant.DEFAULT_SONG_PIC) || !"minio/".equals(picPath.substring(0,6))) {
                continue;
            }
            String filename = picPath.substring(picPath.lastIndexOf("/") + 1);
            minioService.deleteFile(MinioPicPathConstant.SONG_IMAGES_PATH, filename);
        }

        return true;
    }

    /**
     * 获取所有歌手的名字和图片路径
     * @return
     */
    public List<SingerVO> getSingerPicPath() {
        List<Singer> singers = singerMapper.selectList(null);

        List<SingerVO> singerVOList = new ArrayList<>();
        for (Singer singer : singers) {
            SingerVO singerVO = new SingerVO();
            BeanUtils.copyProperties(singer, singerVO); // 把Singer中的属性复制到SingerVO中
            singerVOList.add(singerVO);
        }

        return singerVOList;
    }

    /**
     * 根据性别获取歌手信息
     * @param sex
     * @return
     */
    public Result getSingerBySex(Integer sex) {
        List<Singer> singerList = lambdaQuery()
                .eq(sex != null, Singer::getSex, sex)
                .list();
        return Result.success(singerList);
    }
}
